package com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.example.dante.a17376060_wanghaikang_finaltest.R;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.broadcastReceiver.Receiver;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.domain.Name;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.domain.News;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.domain.User;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.fragment.FragmentKinds;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.fragment.FragmentNews;

import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.useraction.LoginActivity;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.useraction.MyDownLoad;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.useraction.NewsContent;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.useraction.ShouCang;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.utils.HttpUtil;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.utils.UploadUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private DrawerLayout drawerLayout;
    private FragmentManager fragmentManager;
    private FragmentTransaction fragmentTransaction;
    private NavigationView navigationView;
    List<Integer> jieguo;
    private List<User> userlist=new ArrayList<>();
    public static final int CHOOSE_PHOTO=2;
    FragmentNews fragmentNews;
    ImageView home,kinds;
    CircleImageView icon;
    TextView textView;
    String user_name,responseData,ponseData;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    for(Integer i:jieguo){
                        if(i==1){
                            getUserImage(user_name);
                            Toast.makeText(getApplicationContext(),"头像上传成功",Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(getApplicationContext(),"头像上传失败",Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                case 2:
                    for(User user:userlist){
                        if(user.getImage_path()!=null&&!user.getImage_path().equals("")){
                            Bitmap bitmap=BitmapFactory.decodeFile(user.getImage_path());
                            icon.setImageBitmap(bitmap);
                        }else {
                            icon.setImageResource(R.drawable.dog);
                        }
                    }
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initEvent();
    }

    private void initEvent() {
        navigationView=findViewById(R.id.nav_view);
        ActionBar actionBar=getSupportActionBar();
        if(actionBar!=null){
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.you);
        }
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                switch (menuItem.getItemId()){
                    case R.id.user:
                        drawerLayout.closeDrawers();
                        Intent intent=new Intent(MainActivity.this,LoginActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.like:
                        if(Name.USER_NAME!=null) {
                            drawerLayout.closeDrawers();
                            Intent intent1 = new Intent(MainActivity.this, ShouCang.class);
                            startActivity(intent1);
                        }else {
                            Toast.makeText(getApplicationContext(),"请先登录",Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case R.id.local_download:
                        drawerLayout.closeDrawers();
                        Intent intent2=new Intent(MainActivity.this,MyDownLoad.class);
                        startActivity(intent2);
                        break;
                    default:
                        break;
                }
                return true;
            }
        });
    }

    private void openAlbum() {
        Intent intent=new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent,CHOOSE_PHOTO);
    }

    @SuppressLint("ResourceType")
    private void initView() {
        home=findViewById(R.id.home);
        kinds=findViewById(R.id.kinds);
        home.setOnClickListener(this);
        kinds.setOnClickListener(this);
        fragmentNews=new FragmentNews();
        fragmentManager=getSupportFragmentManager();
        fragmentTransaction=fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fragment_main,fragmentNews);
        fragmentTransaction.commit();
        drawerLayout=findViewById(R.id.drawer_layout);
        home.setImageResource(R.drawable.news1);
        Toolbar toolbar=findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        navigationView=findViewById(R.id.nav_view);
        View v=navigationView.getHeaderView(0);
        textView=v.findViewById(R.id.username);
        icon=v.findViewById(R.id.icon_image);
        icon.setOnClickListener(this);
    }
    @SuppressLint("ResourceType")
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.home:
                replaceFragment(new FragmentNews());
                home.setImageResource(R.drawable.news1);
                kinds.setImageResource(R.drawable.kinds);
                break;
            case R.id.kinds:
               replaceFragment(new FragmentKinds());
                kinds.setImageResource(R.drawable.kinds1);
                home.setImageResource(R.drawable.news);
                break;
            case android.R.id.home:
                drawerLayout.openDrawer(GravityCompat.START);
                break;
            case R.id.icon_image:
                if(user_name!=null) {
                    AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
                    dialog.setTitle("");
                    dialog.setMessage("前往相册更换头像？");
                    dialog.setCancelable(false);
                    dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                            } else {
                                openAlbum();
                            }
                        }
                    });
                    dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
                    dialog.show();
                }else {
                    Toast.makeText(getApplicationContext(),"请先登录",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }
    private void replaceFragment(Fragment fragment){
        fragmentManager=getSupportFragmentManager();
        fragmentTransaction=fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fragment_main, fragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent intent=getIntent();
        user_name=intent.getStringExtra("user_name");
        if(user_name!=null) {
            textView.setText(user_name);
            Name.USER_NAME=user_name;
            getUserImage(user_name);
        }
    }

    private void getUserImage(final String user_name) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpUtil.sendOkHttpRequest("http://47.101.175.33:8080/AndroidDataFinalTest/user_touxiang.action?user_name=" + user_name, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        ponseData=response.body().string();
                        JSONTouxiang(ponseData);
                    }
                });
            }
        }).start();
    }

    private void JSONTouxiang(String ponseData) {
        Gson gson = new Gson();
        userlist=gson.fromJson(ponseData, new TypeToken<List<User>>() {
        }.getType());
        Message msg = new Message();
        msg.what = 2;
        handler.sendMessage(msg);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode){
            case CHOOSE_PHOTO:
                if(resultCode==RESULT_OK){
                    if(Build.VERSION.SDK_INT>=19){
                        handleImageOnKitKat(data);
                    }else {
                        handleImageBeforeKitKat(data);
                    }
                }
                break;
            default:
                break;
        }
    }

    private void handleImageBeforeKitKat(Intent data) {
        Uri uri=data.getData();
        String imagePath=getImagePath(uri,null);
        displayImage(imagePath);
    }

    private void handleImageOnKitKat(Intent data) {
        String imagePath=null;
        Uri uri=data.getData();
        if(DocumentsContract.isDocumentUri(this,uri)){
            String docId=DocumentsContract.getDocumentId(uri);
            if("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id=docId.split(":")[1];
                String selection=MediaStore.Images.Media._ID+"="+id;
                imagePath=getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            }else if("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contentUri=ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId));
                imagePath=getImagePath(contentUri,null);
            }
        }else if("content".equalsIgnoreCase(uri.getScheme())){
            imagePath=getImagePath(uri,null);
        }else if("file".equalsIgnoreCase(uri.getScheme())){
            imagePath=uri.getPath();
        }
        displayImage(imagePath);
    }

    private void displayImage(String imagePath) {
        if(imagePath!=null){
            Bitmap bitmap=BitmapFactory.decodeFile(imagePath);
            icon.setImageBitmap(bitmap);
            uploadImage(imagePath);
        }else {
            Toast.makeText(this,"图片获取失败",Toast.LENGTH_SHORT).show();
        }
    }

    private String getImagePath(Uri uri, String selection) {
        String path=null;
        Cursor cursor=getContentResolver().query(uri,null,selection,null,null);
        if(cursor!=null){
            if(cursor.moveToFirst()){
                path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    openAlbum();
                }else {
                    Toast.makeText(this,"你拒绝了权限申请",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }
    public void uploadImage(final String path) {
        if(user_name!=null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    HttpUtil.sendOkHttpRequest("http://47.101.175.33:8080/AndroidDataFinalTest/user_upload.action?user_name=" + user_name + "&&image_path=" + path, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            responseData=response.body().string();
                            parseJSONObject(responseData);
                        }
                    });
                }
            }).start();
        }
    }

    private void parseJSONObject(String responseData) {
        Gson gson = new Gson();
        jieguo=gson.fromJson(responseData, new TypeToken<List<Integer>>() {
        }.getType());
        Message msg = new Message();
        msg.what = 1;
        handler.sendMessage(msg);
    }
}